package com.servlet;

import java.io.*;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*; 
import org.apache.commons.fileupload.servlet.*;

import com.javabean.User;
import com.model.UploadService;

/**
 * Servlet implementation class fileupload
 */
@WebServlet("/files/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    private String filePath = "D:\\DOCSERVER\\upload\\"; // 上传文件的目录  
    private String tempPath = "D:\\DOCSERVER\\upload\\tmp\\"; // 临时文件目录 
    /*
    public void init(ServletConfig config) throws ServletException      
    {
    	super.init(config);          // 从配置文件中获得初始化参数          
    	filePath = config.getInitParameter("filePath");          
    	tempPath = config.getInitParameter("temppath");           
    	ServletContext context = getServletContext();           
    	filePath = context.getRealPath(filePath);          
    	tempPath = context.getRealPath(tempPath);          
    	System.out.println("文件存放目录、临时文件目录准备完毕 ...");      
    }*/
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/plain;charset=utf-8");          
		PrintWriter pw = response.getWriter();
		
		UploadService uls = new UploadService();
		HttpSession session=request.getSession();
		
		try {   
			DiskFileItemFactory diskFactory = new DiskFileItemFactory();   
			// threshold 极限、临界值，即硬盘缓存 1M              
			diskFactory.setSizeThreshold(4 * 1024);              
			// repository 贮藏室，即临时文件目录              
			diskFactory.setRepository(new File(tempPath));  
			ServletFileUpload upload = new ServletFileUpload(diskFactory);
			// 设置允许上传的最大文件大小 4M             
			upload.setSizeMax(4 * 1024 * 1024);     
			// 解析HTTP请求消息头             
			List fileItems = upload.parseRequest(request); 
			Iterator iter = fileItems.iterator();      
			while(iter.hasNext())              
			{       
				FileItem item = (FileItem)iter.next();   
				if(item.isFormField())                  
				{                      
					System.out.println("处理表单内容 ...");  
					processFormField(item, pw);                  
				}else{                     
					System.out.println("处理上传的文件 ..."); 
					processUploadFile(item, pw);  
					String docName = item.getName();
					long docOwner = ((User) request.getSession(true).getAttribute("user")).getUserId();
					String docType = docName.substring(docName.indexOf('.') + 1);
					uls.insertDoc(docName, docOwner, docType);
					response.sendRedirect("DocUp.jsp?flag=successful");
				}              
			}// end while()               
			pw.close();     
			
			}catch(Exception e){ 
				System.out.println("使用 fileupload 包时发生异常 ...");
				response.sendRedirect("DocUp.jsp?flag=failed");
				e.printStackTrace();          
			}// end try ... catch ...  
		}
		private void processFormField(FileItem item, PrintWriter pw) throws Exception      
		{
			String name = item.getFieldName(); 
			String value = item.getString();    
			//pw.println(name + " : " + value + "\r\n");      
		}
		// 处理上传的文件     
		private void processUploadFile(FileItem item, PrintWriter pw) throws Exception     
		{          // 此时的文件名包含了完整的路径，得注意加工一下          
			String filename = item.getName();                 
			System.out.println("完整的文件名：" + filename);  
			
			int index = filename.lastIndexOf("\\");         
			filename = filename.substring(index + 1, filename.length());    
			long fileSize = item.getSize();         
			if("".equals(filename) && fileSize == 0)         
			{                        
				System.out.println("文件名为空 ...");           
				return;          
			}          
			File uploadFile = new File(filePath + "/" + filename);   
			item.write(uploadFile);         
			//pw.println(filename + " 文件上传完毕 ...");   
			//pw.println("文件大小为 ：" + fileSize + "\r\n");
		}  
}
